package com.yydm.serviceacls.controller;

import com.yydm.commonutils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片上传与下载
 */
@RestController
@RequestMapping("/acl/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
//        System.out.println(basePath);
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        String originalFilename = file.getOriginalFilename();//获取文件名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString() + substring;
        File file1 = new File(basePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + s));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().data("s",s);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
//    @PreAuthorize("hasAnyRole('/home','/mall','/user')")
    public void download(String name, HttpServletResponse response) {
        System.out.println(basePath+name);
        try {
            //输入流，读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("/image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();//更新
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
